﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Data;
using System.Diagnostics;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.IO;
using System.Runtime.Versioning;
using AssemblyViewer.Common;

namespace AssemblyViewer.Model
{
    class AssemblyDetailInfo
    {
        public string AssemblyName { get; private set; }

        public List<AssemblyNameInfo> ReferenceAssemblies { get; private set; }

        public String BuildMode { get; private set; }

        public string ProcessorArchitecture { get; private set; }

        public string Framework { get; set; }

        private AssemblyDetailInfo()
        {
        }

        public AssemblyDetailInfo(string filePath)
        {
            LoadAssembly(filePath);
        }

        private void LoadAssembly(string filePath)
        {
            try
            {
                Assembly assembly = Assembly.LoadFile(filePath);
                AssemblyName = assembly.FullName;
                BuildMode = assembly.GetBuildMode();
                Framework = assembly.GetTargetFx();
                ProcessorArchitecture = assembly.GetProcessorArchitecture();
                ReferenceAssemblies = GetRefereneAssembly(assembly, Path.GetDirectoryName(filePath));
            }
            catch (Exception ex)
            {
                AssemblyName = string.Format("该程序集可能不是一个.Net模块的程序集！({0})", ex.Message);
            }
        }

        /// <summary>
        /// 获取引用程序集信息
        /// </summary>
        /// <param name="assembly">输入的程序集</param>
        /// <returns>引用程序集信息</returns>
        private List<AssemblyNameInfo> GetRefereneAssembly(Assembly assembly, string assemblyFilePath = "")
        {
            AssemblyName[] assemblyNames = assembly.GetReferencedAssemblies();

            List<AssemblyNameInfo> lstReferences = new List<AssemblyNameInfo>(assemblyNames.Length);

            var referItems = from anItem in assemblyNames
                             orderby anItem.Name
                             select new AssemblyNameInfo(anItem, assemblyFilePath);

            lstReferences.AddRange(referItems);

            return lstReferences;
        }
    }
}
